package com.xzy.sms.web.system.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xzy.sms.web.system.dao.ConfigDao;
import com.xzy.sms.web.system.entity.Config;
import com.xzy.sms.web.system.service.interfaces.IBussConfig;
import com.xzy.sms.web.system.utils.ConfigUtils;
import com.xzyframework.SpringContextHolder;

/**
 * 配置项service类
 * 
 * @author macong
 * @since 1.0
 * @version 2014-10-22 macong
 */
@Component
@Transactional
public class ConfigService {
    
    protected Logger logger = LoggerFactory.getLogger(getClass());
    
    /** 数据同步租户id */
    public final static String TENANT_ID = "TENANT_ID";
    
    /** 数据同步定时器 */
    public final static String DATASYN_CRONEXP = "DATASYN_CRONEXP";
    
    /** 配置dao */
    @Autowired
    private ConfigDao configDao;
    
    /** 业务配置bean */
    private IBussConfig bussConfig;
    
    /**
     * 获取业务配置项实例
     * @return BussConfig
     */
    public IBussConfig getBussConfig() {
        if (null == bussConfig) {
            Map<String, IBussConfig> map = SpringContextHolder.getCtx().getBeansOfType(IBussConfig.class);
            if (!map.isEmpty()) {
                for (Entry<String, IBussConfig> e : map.entrySet()) {
                    bussConfig = e.getValue();
                    break;
                }
            }
        }
        return bussConfig;
    }
    
    /**
     * 查询一个配置信息
     * @param id xx
     * @return xx
     */
    @Transactional(readOnly = true)
    public Config findConfig(String id) {
        Config conf = configDao.getOne(id);
        return conf;
    }
    
    /**
     * 保存（这里需要清除hibernate缓存，否则会不一致）
     * @param config xx
     */
    public void saveConfig(Config config) {
        configDao.save(config);
        ConfigUtils.removeCache(config.getId());
    }
    
    /**
     * 根据配置项查询配置
     * @return List<Config>
     */
    @Transactional(readOnly = true)
    public List<Config> findAll() {
        Map<Object, Config> map = getAllConfig();
        if (null == map) {
            return Lists.newArrayList();
        }
        Iterator<Entry<Object, Config>> iterator = map.entrySet().iterator();
        List<Config> lstConfig = new ArrayList<Config>();
        while (iterator.hasNext()) {
            Entry<Object, Config> entry = iterator.next();
            if (null != entry.getKey()) {
                Config config = configDao.getOne(String.valueOf(entry.getKey()));
                if (null == config) {
                    config = entry.getValue();
                } else {
                    config.setCnName(entry.getValue().getCnName());
                    config.setShowType(entry.getValue().getShowType());
                    config.setGroup(entry.getValue().getGroup());
                    config.setRemarks(entry.getValue().getRemarks());
                    config.setSort(entry.getValue().getSort());
                    config.setDisplay(entry.getValue().isDisplay());
                    config.setIssued(entry.getValue().isIssued());
                }
                lstConfig.add(config);
            }
        }
        Collections.sort(lstConfig, new Comparator<Config>() {
            
            @Override
            public int compare(Config o1, Config o2) {
                return o1.getSort() > o2.getSort() ? 1 : -1;
            }
        });
        return lstConfig;
    }
    
    /**
     * 根据配置项查询下发配置
     * @return List<Config>
     */
    @Transactional(readOnly = true)
    public List<Config> findAllIssued() {
        List<Config> issuedConfigs = Lists.newArrayList();
        for (Config config : this.findAll()) {
            if (config.isIssued()) {
                issuedConfigs.add(config);
            }
        }
        return issuedConfigs;
    }
    
    /**
     * 获取所有业务配置项
     * @return map
     */
    private Map<Object, Config> getAllConfig() {
        if (null != getBussConfig()) {
            Map<Object, Config> map = getBussConfig().getAllConfig();
            if (null != map) {
                return map;
            }
        }
        return Maps.newHashMap();
    }
    
    /**
     * 获取业务配置项默认值
     * @param ckey ckey
     * @return map
     */
    public String getBussDefValue(String ckey) {
        if (null != getBussConfig()) {
            return getBussConfig().getDefValue(ckey);
        }
        return null;
    }
    
    /**
     * 获取业务配置项默认值
     * @param ckey ckey
     * @return map
     */
    public String getBussRemarks(String ckey) {
        if (null != getBussConfig()) {
            return getBussConfig().getRemarks(ckey);
        }
        return "";
    }
    
    /**
     * 保存配置信息
     * @param configs configs
     */
    public void saveSysconfig(List<Config> configs) {
        for (Config config : configs) {
            // 清除数据库缓存
            ConfigUtils.removeCache(config.getId());
        }
        configDao.saveAll(configs);
    }
    
}
